package com.example.demo.api;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)){
            System.out.println("登录失败，用户名或密码错误");
            return new User();
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        return user;
    }

    @ResponseBody
    @PostMapping("/register")
    public Object register(String username,String password){
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            return new User();
        }
    }

    @ResponseBody
    @GetMapping("/userinfo")
    //获取网页中是否有用户的会话信息，如果有，则说明已经登录
    public Object getUserInfo(HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            User newUser = userMapper.selectByName(user.getUsername());

            return newUser;
        }catch (NullPointerException e){
            return new User();
        }
    }


}
